<?php
namespace hyang;
class Element{
    // 参数- option[select_element/value/text/select_attr(array/string-)/selected],$param(array/callable)
    public function select($param,$option=null)
    {
        if(is_callable($param)) $data = $param();
        else $data = $param;
        if(!is_array($data)) return;
        $value = isset($option['value'])? $option['value']:'';
        if(empty($value)){
            if(isset($data[0]) && is_array($data[0])){
                $tmpArr = array_keys($data[0]);
            }else{
                $tmpArr = array_keys($data);                
            }
            $value = $tmpArr[0];
        }
        $text = isset($option['text'])? $option['text']:$value;
        $html = '';
        $selected = '';
        if(isset($option['selected'])) $selected = $option['selected'];
        foreach($data as $v){
            $optionValue = $v[$value];
            $html .= '<option value="'.$optionValue.'"'.($optionValue == $selected? ' selected="selected"':'').'>'.$v[$text].'</option>'; 
        }
        if($html){
            if(isset($option['select_element'])) $html = $option['select_element'].$html.'</select>';
            else{
                $selectHtml = '<select';
                if(isset($option['select_attr'])) $selectHtml .= $this->_attrglue($option['select_attr']);
                $selectHtml .= '>'.$html.'</select>';
                $html = $selectHtml;
            }
        }
        return $html;
    }
    // $param[array/string/callback]
    private function _attrglue($param)
    {
        if(is_callable($param)) $data = $param();
        else $data = $param;
        $html = '';
        if(is_array($data)){
            $attr = [];
            foreach($data as $key=>$val){
                $attr[] = is_numeric($key)? $val:$key.'="'.$val.'"';
            }
            if($attr) $html .= ' '.implode(' ',$attr);
        }
        elseif(is_string($data) && $data) $html = ' '.$data;
        return $html;              
    }
}